/*
 * 日期：2019.7.18
 * 韩宇航于哈工大（威海）研学楼
 * 
 * 本程序适用于Arduino NANO控制四个直流减速电机，18650 3.7V*2供电
 * 
 * 7.18：
 * 程序整体编写完毕，等待具体调试转向指令（占空比具体数值）
 * 
 * 7.19：
 * 转向指令调试完毕，转向真车试跑成功，针对张教授给的贼窄的跑道，
 * 降低了前进后退的速度，为防止猝不及防的竞速模式，添加了全速前进、后退
 * 
 * 另：可以考虑降低进一步降低左右转的速度以便于控制
 */
 
int vA,vB,vC,vD;                //定义4个电机的速度变量
int dA,dB,dC,dD;                //电机旋转方向
int dir;                        //小车运动方向

void setup() 
{
  pinMode(2, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  Serial.begin(9600);
}

void loop() 
{
  if(Serial.available()>0)        //查询串口
  {
    dir = Serial.read();          //将串口接收的赋给运动方向变数据量
  }

  switch(dir)
  {
    case 0x00:                   //停
    dA = LOW;vA = 0;
    dB = LOW;vB = 0;
    dC = LOW;vC = 0;
    dD = LOW;vD = 0;
    break;

    case 0x01:                   //前进
    dA = HIGH;vA = 100;
    dB = HIGH;vB = 100;
    dC = HIGH;vC = 100;
    dD = HIGH;vD = 100;
    break;

    case 0x02:                   //后退
    dA = LOW;vA = 150;
    dB = LOW;vB = 150;
    dC = LOW;vC = 150;
    dD = LOW;vD = 150;
    break;

    case 0x03:                  //左转
    dA = LOW;vA = 0;
    dB = HIGH;vB = 100;
    dC = LOW;vC = 150;
    dD = HIGH;vD = 100;
    break;

    case 0x04:                   //右转
    dA = HIGH;vA = 100;
    dB = LOW;vB = 0;
    dC = HIGH;vC = 100;
    dD = LOW;vD = 150;
    break;

    case 0x05:                   //全速前进
    dA = HIGH;vA = 0;
    dB = HIGH;vB = 0;
    dC = HIGH;vC = 0;
    dD = HIGH;vD = 0;
    break;

    case 0x06:                  //全速后退
    dA = LOW;vA = 255;
    dB = LOW;vB = 255;
    dC = LOW;vC = 255;
    dD = LOW;vD = 255;
    break;
  }
    
  digitalWrite(2, dA);          //执行
  analogWrite(3,vA);
  digitalWrite(4, dB);
  analogWrite(5,vB);
  digitalWrite(7, dC);
  analogWrite(6,vC); 
  digitalWrite(8, dD);
  analogWrite(9,vD);
}



/*********************************************************
 * 
 * 
 *       帅哥李老师保佑，BUG退散（手动滑稽）
 * 
 * 
 * *******************************************************/
